package core;

import constant.Constant;
import util.HttpUtils;
import util.LogUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.util.concurrent.Callable;

/**
 * Created by Lenovo
 * DATA:2023/10/28
 **/
public class DownloaderTask implements Callable<Boolean> {
    private String url;//下载地址

    private long startPos;//下载的起始位置

    private long endPos;//下载的结束位置

    private int part;//标注当前是哪一部分

    public DownloaderTask(String url, long startPos, long endPos, int part) {
        this.url = url;
        this.startPos = startPos;
        this.endPos = endPos;
        this.part = part;
    }

    @Override
    public Boolean call() throws Exception {
        //获取文件名
        String httpFileName = HttpUtils.getHtpFileName(url);
        //分块的文件名
        httpFileName=httpFileName+".temp"+part;
        //下载路径
        httpFileName= Constant.PATH+httpFileName;
        //获取分块下载的链接
        HttpURLConnection httpURLConnection = HttpUtils.getHttpURLConnection(url,startPos,endPos);
        try(
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
                RandomAccessFile randomAccessFile = new RandomAccessFile(httpFileName,"rw");
        ){
            int len = -1;
            byte[] buffer = new byte[Constant.BYTE_SIZE];
            while ((len = bufferedInputStream.read(buffer)) != -1) {
                //1秒内下载数据之和，通过原子类进行操作
                DownloadInfoThread.downSize.add(len);
                randomAccessFile.write(buffer, 0, len);
            }

        }catch (FileNotFoundException e){
            LogUtils.error("下载的文件不存在{}", url);
            return false;
        }catch (Exception e){
            LogUtils.error("下载失败");
            return false;
        }finally {
            httpURLConnection.disconnect();

        }

        return null;
    }
}
